<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
            body{
                padding: 20px;
            }
            .index{
                min-width: 20%;
                /* height:100%; */
                margin-right:20px;
                border: 1px solid #409EFF;
            }
            .response{
                border: 1px solid #409EFF;
            }
            label{
                display: inline-block;
                min-width: 15%;
                line-height: 32px;
                vertical-align: middle;
            }
			.aindex{
				color: #409EFF;
                display: block;
                text-align: right;direction: rtl;
                /* font-size:80px; */
                /* margin: 40px; */
                /* max-width: 100px;  */
                overflow:hidden;
	white-space:nowrap;
	text-overflow: ellipsis;

				text-decoration: none;
			}
            a:hover { 
                    border: 1px solid #409EFF;
                } 
            a:active { 
                    color: #f00;
                } 
            a:visited { 
                color:#f00; 
            } 
			.main{
				width: 60%;
                text-align: left;
			}
            .flex{
                display: flex;
                min-height: 40px;
                padding: 2px;
            }
            .right{
                text-align: right;
            }
            .red{
                color:red;
            }
            .hide{
                display:none;
            }
		</style>
    <script src="js/FileSaver.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
        <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script> -->
    <script src="https://cdn.jsdelivr.net/npm/ant-design-vue@1.4.10/dist/antd.min.js"></script>
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js"></script> -->
    <!-- <script src="https://res.wx.qq.com/open/js/jweixin-1.6.0.js"></script>     -->
    <link href="https://cdn.jsdelivr.net/npm/ant-design-vue@1.4.10/dist/antd.min.css" rel="stylesheet"
        type="text/css" />
    <!-- <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js"></script> -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/ant-design-vue@2.2.2/dist/antd.min.js"></script> -->
    <!-- <script src="https://cdn.jsdelivr.net/npm/moment@2.29.1/min/moment.min.js"></script> -->
    <!-- <link href="https://cdn.jsdelivr.net/npm/ant-design-vue@2.2.2/dist/antd.min.css" rel="stylesheet" -->
        <!-- type="text/css" /> -->
	</head>
	<body>
		<div id='app' class="flex">
                <div class="index">
                    <a-row v-for="(v,k) in indexBox">
                        <a-col :span="23">
                            <a class="aindex" href="javascript:;" @click="init(k)" >
                                {{v}}
                            </a>
                        </a-col>
                        <a-col :span="1">
                            <a-icon type="close" title="点击删除" class="red" @click="remove(k)"/>
                        </a-col>
                    </a-row>
                </div>
            <div class="main">
                <div>                    
                    <label>Method:</label>
                    <a-dropdown>
                        <a-menu slot="overlay" @click="handleMenuClick">
                            <a-menu-item key="POST">POST</a-menu-item>
                            <a-menu-item key="GET">GET</a-menu-item>
                            <a-menu-item key="PUT">PUT</a-menu-item>
                            <a-menu-item key="DELETE">DELETE</a-menu-item>
                        </a-menu>
                        <a-button> {{method}} <a-icon type="down" /> </a-button>
                      </a-dropdown>
                    <!-- <a-select v-model:value="method">
                        <a-menu-item key="POST">POST</a-menu-item>
                        <a-menu-item key="GET">GET</a-menu-item>
                        <a-menu-item key="PUT">PUT</a-menu-item>
                        <a-menu-item key="DELETE">DELETE</a-menu-item>
                    </a-select> -->
                </div>
                <div class="flex">
                    <label>Url：</label>
                    <a-input v-model:value="url" ></a-input>
                </div>
                <div class="flex">
                    <label>Headers：</label>
                    <div>
                        <div v-for="(item,index) in headers" class="flex">
                                <!-- <label>{{item.k}}：</label> -->
                                <a-input name='header-key' v-model:value="item.k" placeholder="Header Key"></a-input>
                                <a-input  v-model:value="item.v" placeholder="Header Vlaue"></a-input>
                                <a-icon type="close" title="点击删除" class="red" @click="removeHeader(item.k)"/>
                        </div>
                    </div>
                    
                    <div><a-button @click="addHeader">添加</a-button></div>
                </div>
                <div class="flex">
                    <label>Body：</label>
                    <a-textarea id="textarea" ref="textarea" v-model:value="body" :rows="6" >                        
                    </a-textarea>
                </div>
                <div class="right"><a-button @click="send">发送</a-button></div>
                <div class="flex">
                    <label>Response：{{responseCode}}</label>
                    
                    <a-textarea class="response" :value="response" :rows="15" >
                    </a-textarea>
                    <!-- <p class="response">
                        {{response}}
                    </p> -->
                </div>
            </div>
            <div class="right">
                <a-button @click="exportLog">导出记录<a-icon type="download" /></a-button>
                <!-- <a-upload name="file" @change="importLog" :multiple="true">
                    <a-button> 导入记录<a-icon type="import" />  </a-button>
                </a-upload> -->
                <input type="file" ref="import" class='hide' @change="fileImport"/>
                <a-button @click="openFileDialog"> 导入记录<a-icon type="import" />  </a-button>
                
                <a-button @click="openUrlDialog"> 在线导入<a-icon type="import" />  </a-button>
            </div>
		</div>
		<script type="text/javascript">           
            
            let app = new Vue({
              el: '#app',
              data: {
                url:'',
                method:'GET',
                body:'',
                response:'',
                responseCode:0,
                headers:[],
                indexBox:{}
              },
              mounted:async function(){
               this.indexBox=JSON.parse(localStorage.getItem('http-log'))||{};
               let importUrl=this.getQueryString('importUrl');
               if(importUrl&&confirm("是否确认从地址导入日志？")){
                   this.urlImport(importUrl);
               }
              },
              methods: {
                init(index){
                    let item=JSON.parse(localStorage.getItem(`item-${index}`));
                    console.log(index,item)
                    if(!item)return;
                    this.url=item.url;
                    this.method=item.method;
                    this.body=item.body;
                    this.headers=Object.keys(item.headers).map((key)=>{
                        return {k:key,v:item.headers[key]}
                    });
                },
                async send(){
                    if(!this.url)return;
                    let res;
                    if(this.method==="GET"){
                        res = await fetch(this.url)
                    }else{
                        let headers = {}
                        this.headers.map(function (item) {
                            headers[item.k] = item.v
                        });
                        res = await fetch(this.url,{
                            "method":this.method,
                            "headers":headers,
                        　　"body":this.body
                        })
                    }
                    this.add();
                    this.responseCode=res.status;
                    if(this.responseCode!=200){
                        this.response=null;
                        return;
                    }
                    let json=await res.json()
                    this.response=JSON.stringify(json,null,'\t');
                },
                add(){
                    let keys=Object.keys(this.indexBox);
                    let maxIndex=keys[keys.length-1]||0;
                    let key=1+parseInt(maxIndex);
                    this.indexBox[key]=this.url;
                    let headers = {}
                    this.headers.map(function (item) {
                        headers[item.k] = item.v
                    });
                    let obj={
                        url:this.url,
                        method:this.method,
                        headers:headers,
                        body:this.body,
                    };
                    localStorage.setItem(`item-${key}`,JSON.stringify(obj));
                    localStorage.setItem(`http-log`,JSON.stringify(this.indexBox));
                },
                remove(key){
                  console.log(key);
                  this.$delete(this.indexBox, key);
                    // delete this.indexBox[key];
                    localStorage.setItem(`http-log`,JSON.stringify(this.indexBox));
                    localStorage.removeItem(`item-${key}`);
                },
                addHeader(){
                    this.headers.push({});
                    console.log(this.headers)
                },
                removeHeader(key){
                    // delete this.headers[key];
                  this.headers.some((item,i) => {
                    if(item.k==key){
                        this.headers.splice(i,1)
                        return true;
                    }
                  })
                },
                exportLog(){
                    let logs = [];
                    Object.keys(this.indexBox).map(function (index) {
                        logs.push(JSON.parse(localStorage.getItem(`item-${index}`)));
                    });
                    let data={
                        indexBox:this.indexBox,
                        logs:logs
                    };
                    let blob = new Blob([JSON.stringify(data)], { type: "" });
                    saveAs(blob,'http-log.json' );
                },
                openFileDialog(){
                    let fileInput=this.$refs.import;
                    fileInput.click();
                },
                openUrlDialog(){
                    var url = prompt("请输入在线文件地址：");
                    this.urlImport(url);
                },
                batchImport(data){
                    let _this=this;
                    let keys=Object.keys(_this.indexBox);
                    let maxIndex=parseInt(keys[keys.length-1]||0);
                    console.log(maxIndex,data);
                    data.logs.map(function (item) {
                        maxIndex++;
                        localStorage.setItem(`item-${maxIndex}`,JSON.stringify(item));
                        // _this.indexBox[maxIndex]=item.url;
                        Vue.set(_this.indexBox, maxIndex, item.url);
                    });
                    localStorage.setItem(`http-log`,JSON.stringify(_this.indexBox));
                    
                },
                async urlImport(url){
                    let _this=this;
                    var res = await fetch(url);
                    let data= await res.json()
                    _this.batchImport(data);
                },
                fileImport(){
                    let _this=this;
                    let file=this.$refs.import.files[0];
                    var reader = new FileReader();//新建一个FileReader
                    reader.readAsText(file, "UTF-8");//读取文件 
                    reader.onload = function(evt){ //读取完文件之后会回来这里
                        var fileString = evt.target.result; // 读取文件内容
                        let data=JSON.parse(fileString);
                        _this.batchImport(data);
                    }
                },
                handleMenuClick(e) {
                    this.method=e.key;
                },
                async httpGet(url,data){
                    header={'Authorization':'Bearer '+this.accessToken}
                    var res = await fetch(url,{headers:header});
                    if(res.status!=200)return null;
                    return await res.json()
                },
                async httpPost(url,data){
                    header={
                        'Content-Type': 'application/json',
                        'Authorization':'Bearer '+this.accessToken
                    }
                    var res = await fetch(url,{
                        method:"POST",
                        headers:header,
                    　　body:JSON.stringify(data)
                    })
                    if(res.status!=200)return null;
                    return await res.json()
                },
                filter(inputValue, path) {
                  console.log(inputValue,path);
                  return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
                },
                getCookie(name){
                    var reg = RegExp(name + '=([^;]+)');
                    var arr = document.cookie.match(reg);
                    if (arr) {
                        return arr[1];
                    } else {
                        return '';
                    }
                },                
                getQueryString(key){
                    var reg = new RegExp("(^|&)"+ key +"=([^&]*)(&|$)");
                    var r = window.location.search.substr(1).match(reg);
                    if(r!=null)return  unescape(r[2]); return null;
                },
              }
            });
		</script>
	</body>
</html>